/**
Copyright (c) 2008 New Gonzo <john@newgonzo.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
**/



package com.newgonzo.cannonball.dom.html
{
	import flash.utils.Dictionary;
		
	import com.adobe.net.URI;
	
	import com.newgonzo.cannonball.w3c.dom.IDOMImplementation;
	import com.newgonzo.cannonball.w3c.dom.IElement;
	import com.newgonzo.cannonball.w3c.dom.INode;
	
	import com.newgonzo.cannonball.w3c.dom.traversal.IDocumentTraversal;
	import com.newgonzo.cannonball.w3c.dom.traversal.ITreeWalker;
	import com.newgonzo.cannonball.w3c.dom.traversal.INodeFilter;
	
	import com.newgonzo.cannonball.w3c.dom.css.IDocumentCSS;
	import com.newgonzo.cannonball.w3c.dom.css.ICSSStyleSheet;
	import com.newgonzo.cannonball.w3c.dom.css.IDOMImplementationCSS;
	import com.newgonzo.cannonball.w3c.dom.stylesheets.IStyleSheet;
	import com.newgonzo.cannonball.w3c.dom.stylesheets.IStyleSheetList;
	import com.newgonzo.cannonball.w3c.dom.stylesheets.ILinkStyle;
	
	import com.newgonzo.cannonball.w3c.dom.html.IHTMLDocument;
	import com.newgonzo.cannonball.w3c.dom.html.IHTMLElement;
	
	import com.newgonzo.cannonball.dom.css.DocumentCSS;
	import com.newgonzo.cannonball.dom.Document;
	import com.newgonzo.cannonball.dom.traversal.TreeWalker;
	import com.newgonzo.cannonball.dom.stylesheets.StyleSheet;
	import com.newgonzo.cannonball.dom.stylesheets.StyleSheetList;
	
	import com.newgonzo.commons.utils.URIUtil;
	
	public class HTMLDocument extends DocumentCSS implements IHTMLDocument
	{
		default xml namespace = xhtmlns;
		
		public function HTMLDocument(owner:IDOMImplementation)
		{
			super(owner);
		}
		
		override public function set content(value:*):void
		{
			super.content = value;
			//parseEmbeddedStyles();
		}
		
		override public function createElement(tagName:String):IElement
		{
			// xhtml is case-sensitive
			var elem:HTMLElement;
			
			switch(tagName)
			{
				case "html":
					elem = new HTMLHtmlElement();
					break;
					
				case "link":
					elem = new HTMLLinkElement();
					break;
					
				case "style":
					elem = new HTMLStyleElement();
					break;
					
				case "a":
					elem = new HTMLAnchorElement();
					break;
					
				case "img":
					elem = new HTMLImageElement();
					break;
					
				case "p":
					elem = new HTMLParagraphElement();
					break;
					
				case "div":
					elem = new HTMLDivElement();
					break;
					
				case "span":
					elem = new HTMLSpanElement();
					break;
					
				case "h1":
				case "h2":
				case "h3":
				case "h4":
				case "h5":
				case "h6":
					elem = new HTMLHeadingElement();
					break;
					
				case "hr":
					elem = new HTMLHRElement();
					break;
					
				case "ul":
					elem = new HTMLUListElement();
					break;
					
				case "ol":
					elem = new HTMLOListElement();
					break;
					
				case "li":
					elem = new HTMLLIElement();
					break;
				
				case "object":
					elem = new HTMLObjectElement();
					break;
					
				case "param":
					elem = new HTMLParamElement();
					break;
					
				case "base":
					elem = new HTMLBaseElement();
					break;
					
				default:
					elem = new HTMLElement();
					break;
			}
			
			return elem;
		}
		
		public function set title(value:String):void
		{
			
		}
		
		public function get title():String
		{
			return content.head.title.text();
		}
		
		public function get domain():String
		{
			return "";
		}
		
		public function get referrer():String
		{
			return "";
		}
		
		public function get body():IHTMLElement
		{
			return getElement(content.body[0]) as IHTMLElement;
		}
		
		public function get base():IElement
		{
			var baseXml:XMLList = content.head.base;
			
			if(!baseXml.length())
			{
				var docUri:URI = new URI(documentURI);
				docUri.chdir("./");
				
				// content.head.* gets the list of children
				// that we want to append to
				content.head.* += <base href={docUri}/>;
			}
			
			return getElement(content.head.base[0]);
		}
		
		override public function get styleSheets():IStyleSheetList
		{
			var list:StyleSheetList = new StyleSheetList();
			
			var element:ILinkStyle;
			var sheet:IStyleSheet;
			
			var elements:Array = this.styleLinks;
			
			for each(element in elements)
			{
				list.push(element.styleSheet);
			}
			
			return list;
		}
		
		public function get styleLinks():Array
		{
			return getElements(content.descendants("link").(hasOwnProperty("@rel") && @rel.toLowerCase() == "stylesheet"));	
		}
		
		public function get styleElements():Array
		{
			return getElements(content.descendants("style"));
		}
		
		public function get images():Array
		{
			return getElements(content.descendants("img"));
		}
		
		public function get anchors():Array
		{
			return getElements(content.descendants("a").(hasOwnProperty("@name") || hasOwnProperty("@id")));
		}
		
		public function get links():Array
		{
			return getElements(content.descendants("a").(hasOwnProperty("@href")));
		}
		
		public function get forms():Array
		{
			return getElements(content.descendants("form"));
		}
		
		public function get applets():Array
		{
			return getElements(content.descendants("object"));
		}
		
		/**
		* With [HTML 4.01] documents, this method returns the (possibly empty) 
		* collection of elements whose name value is given by elementName.
		*/
		public function getElementsByName(elementName:String):Array
		{
			return getElements(content.descendants().(hasOwnProperty("@name") && @name == elementName));
		}
		
		public function createStyleSheet(type:String = "text/css", media:String = ""):IStyleSheet
		{
			var newSheet:StyleSheet;
			
			switch(type)
			{
				// only css is supported
				case "text/css":
				default:
					newSheet = (implementation as IDOMImplementationCSS).createCSSStyleSheet(media) as StyleSheet;
					break;
			}
			
			newSheet.type = type;
			return newSheet;
		}
		
		/*	
		protected function parseEmbeddedStyles():void
		{
			var cssStyleSheet:ICSSStyleSheet;
			var elements:Array = this.styleElements;
			var element:HTMLStyleElement;
			var media:String;
			
			for each(element in elements)
			{
				media = element.styleSheet.media;
				
				cssStyleSheet = cssDocument.parseStyleSheet(element.textContent, media);
				appendCSSStyleSheet(cssStyleSheet, media);
			}
		}
		*/
		
		override public function resolve(path:String):String
		{
			// for now, don't resolve fragments
			if(URIUtil.isFragment(path))
			{
				return path;
			}
			
			var uri:URI;
			var baseElem:HTMLBaseElement = base as HTMLBaseElement;
			
			if(baseElem.href)
			{
				uri = new URI(path);
				uri.makeAbsoluteURI(new URI(baseElem.href));
			}
			else
			{
				uri = new URI(super.resolve(path));
			}
			
			return uri.toString();
		}
		
		override public function toString():String
		{
			return formatToString("HTMLDocument", "title", "base");
		}
		
		override protected function createDefaultContent():XML
		{
			return <html><head><title></title></head><body></body></html>;	
		}
	}
}
